/**
 * @module utils/ImageUtil
 * @desc 图标加载工具
 */

import { randomUUID } from '../../../mapUtils/RandomUtil';

// 图片配置
var timer = null;
var loadedImages = {};
var loadedImageContents = {};
var loadingImages = {};
var loadedImageMapping = {};


/**
 * 重新加载地图图层
 * 解决图片加载成功后未能更新到地图上的问题
 * @param {*} map 地图对象
 */
function reloadTileCache(map) {
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    for (let cache of Object.values(map.style._sourceCaches)) {
      if (cache._source.type === 'raster') {
        continue;
      }
      cache.reload();
    }
  }, 500);
}

/**
 * 加载图标
 * @param {*} map 地图对象
 * @param {String} customimageid 自定义图标Id
 * @param {String} url 图标路径
 */
export function loadImage(map, customimageid, url) {
  return new Promise((resolve, reject) => {
    if (loadedImages[url]) {
      if (!map.style.getImage(loadedImages[url])) {
        map.addImage(loadedImages[url], loadedImageContents[url]);
      }
      resolve(loadedImages[url]);
    } else if(loadingImages[url]) {
      resolve(true);
    }else{
      loadingImages[url] = true;
      map.loadImage(url, (error, image) => {
        delete loadingImages[url];
        if (error) {
          reject(error);
        } else {
          var imageid = customimageid || `image_${randomUUID()}`;
          if (!map.style.getImage(imageid)) {
            map.addImage(imageid, image);
            loadedImages[url] = imageid;
            loadedImageContents[url] = image;
          }
          loadedImageMapping[imageid] = {
            url: url,
            image: image
          };
          reloadTileCache(map);
          resolve(imageid);
        }
      });
    }
  });
}

/**
 * 添加图标
 * @param {*} impl 地图实现
 * @param {*} id 图标Id
 * @param {*} url 图标路径
 */
export function addImage(impl, id, url) {
  return new Promise((resolve) => {
    var images = impl.map.listImages();
    if (images.indexOf(id) >= 0) {
      // 图片已存在，直接返回
      console.log('图片已存在');
      resolve({
        id,
        image: impl.map.style.getImage(id)
      });
    } else {
      loadImage(impl, id, url).then(() => {
        resolve({ id, image: impl.map.style.getImage(id) });
      });
    }
  });
}

/**
 * 加载雪碧图
 * @param {*} impl 地图实现
 * @param {*} image 雪碧图图片路径
 * @param {*} json 雪碧图描述数据路径
 */
export function loadSpriteImage(impl, image, json) {
  window.SGMap.spriteSheet({
    image: image,
    json: json,
    callback: (err, data) => {
      if (!err) {
        Object.keys(data).forEach((key) => {
          let imageSource = data[key];
          impl.map.addImage(key, imageSource.data, { pixelRatio: imageSource.pixelRatio, sdf: imageSource.sdf });
        });
      }
    }
  });
}


export function exportLoadReport() {
  return {
    loadedImages,
    loadingImages,
    loadedImageContents,
    loadedImageMapping
  };
}